home *** CD-ROM | disk | FTP | other *** search
/ Mac-Source 1994 July / Mac-Source_July_1994.iso / C and C++ / Science⁄Math / VideoToolbox / VideoToolboxSources / VBLInstall.c < prev    next >
Text File  |  1993-07-09  |  12KB  |  274 lines

  1. /*
  2. VBLInstall.c
  3.  
  4. This is the Apple-recommended way of synchronizing your program to a video
  5. display. In the Macintosh, interrupt service routines run at a high processor
  6. priority, i.e. they block interrupts while they run, so Apple advises that they
  7. be very quick, to avoid missing interrupts. That is the approach taken here,
  8. using the interrupt service routines solely to bump a frame counter and set a
  9. newFrame flag to true. Typically your main program will iteratively test the
  10. newFrame flag and, when it's true, clear it and do some action that you want to
  11. do once per frame, in synch with the video frames.
  12.  
  13. OSErr VBLInstall(VBLTaskAndA5 *vblData,GDHandle device,int frames)
  14.  
  15. The first argument is a pointer to a user-supplied data structure. "device" is a
  16. handle to video screen that you want to synchronize to, or NULL if you want to
  17. synchronize to the System VBL rate (usually 60.15 Hz). The last argument
  18. specifies how many times "frames" you want the interrupt to occur.
  19.  
  20. Here's a minimal program, extracted from NoiseVBL.c, that uses these routines to
  21. show a movie, with a new image on each video frame:
  22.  
  23.     VBLTaskAndA5 noiseVBL;
  24.     GDHandle device=GetMainDevice();
  25.     int frames=100,error;
  26.  
  27.     noiseVBL.subroutine=NULL;                // request default subroutine
  28.     error=VBLInstall(&noiseVBL,device,frames);
  29.     if(error)PrintfExit("VBLInstall error %d\n",error);
  30.     noiseVBL.vbl.vblCount=1;    // enable the interrupt service routine
  31.     while(noiseVBL.framesLeft){
  32.         if(noiseVBL.newFrame){
  33.             noiseVBL.newFrame=0;
  34.             CopyBitsQuickly((BitMap *)&(movie[noiseVBL.framesLeft])
  35.                 ,(BitMap *)*((CGrafPtr)window)->portPixMap
  36.                 ,&noiseImage[0].bounds,&window->portRect,srcCopy,NULL);
  37.         }
  38.     }
  39.     VBLRemove(&noiseVBL);
  40.  
  41. Apple warns that interrupt service routines and any data that they access must
  42. be locked into memory, not swapped out, e.g. due to operation of the Memory
  43. Manager or Virtual Memory. It is dangerous to allow your compiler to install
  44. debugging code into interrupt service routines. It is VERY important that you
  45. call VBLRemove() before quitting. Once installed, slot-based interrupt tasks
  46. keep going forever. (Turning off vblData->vbl.vblCount disables the routine, but
  47. doesn't remove it.) The tasks are not removed by the Finder or System when your
  48. application finishes, even though the interrupt service routine's code and data
  49. will probably be overwritten.
  50.  
  51. Actually, things aren't that bad, because I've added a call to _atexit()
  52. requesting that all the VBL tasks installed by VBLInstall() be removed whenever
  53. the program terminates, whether normally or abnormally. This prevents the
  54. otherwise very annoying crash that would accompany premature termination, e.g.
  55. by typing command-., while the VBL task is active.
  56.  
  57. Writing an interrupt service routine, to be called once per video frame, is
  58. slightly tricky. VBLInterruptServiceRoutine does all the dirty work, and then
  59. calls a user-supplied subroutine that does whatever you want. If all you want to
  60. do is advance a frame counter until you reach the desired number of frames then
  61. you may wish to use the default FrameSubroutine() instead of writing your own.
  62. Put the address of whatever routine you want to use into the "subroutine"
  63. element of the VBLTaskAndA5 structure, or, to request use of FrameSubroutine,
  64. supply the address NULL.
  65.  
  66. FrameSubroutine() uses Timer.c. If this program runs on an old System (pre
  67. 6.05?) lacking the Revised Time Manager, which Timer.c requires, then
  68. SimpleVBLSubroutine() will be used instead. The Timer is used to discard
  69. spurious interrupts that occur within 5 ms of the previous. This is necessary
  70. because some of the Apple video cards generate several interrupts during the
  71. vertical blanking interval, even though Apple's documentation clearly indicates
  72. that they should only generate one. The fix (holding off for 5 ms) was suggested
  73. by Raynald Comtois.
  74.  
  75. The 1992 Apple "Inside Macintosh: Processes" book explains how to task to be
  76. performed each time your video device produces a vertical blanking level (i.e.
  77. between video frames). It's quite tricky. Therefore I wrote a generic one, that
  78. in turn, calls your custom one, after all the tricky bits have been taken care
  79. of.
  80.  
  81. There are some subtleties to the VBL interrupt service routine. The main one is
  82. that all the Macintosh compilers reference global variables relative to register
  83. A5, but register A5 may have the wrong value (corresponding to a different
  84. application) at interrupt time. So we saved the right value of A5 inside our
  85. structure and restore A5 before calling our Task().
  86.  
  87. A further subtlety is that the new generation of optimizing compilers might
  88. notice that A5 is being modified, so it would be dangerous to access globals at
  89. all in InterruptServiceRoutine(), even though it's safe to do so in Task(). In
  90. fact Task() doesn't use any globals, but it could.
  91.  
  92. The fact that the address of our structure is in register A0 when the interrupt
  93. service routine is called results from the fact that the low level hardware VBL
  94. interrupt is intercepted by the operating system, which then calls our routine.
  95.  
  96. The VBLTaskAndA5 struct extends Apple's VBLTask struct by adding some useful
  97. information at the end. You may choose to copy this, or define your own, adding
  98. more stuff at the end. However, you may not want to bother, considering that
  99. your interrupt service routine can freely access global variables.
  100. Alternatively, I added a generic pointer at the end, which you may use to pass
  101. the address of any stuff that you want for access within your subroutine.
  102.  
  103. Macintosh Technical Note 180 ("Multifinder Miscellanea"), p. 5 says: 
  104. "GetVBLRec() returns the address
  105. of the VBLRec associated with our VBL task. This works because on entry into the
  106. VBL task, A0 points to the theVBLTask field in the VBLRec record, which is the
  107. first field in the record and that is the address we return. Note that this
  108. method works whether the VBLRec is allocated globally, in the heap...or...on the
  109. stack. ... This trick allows us to get to the saved A5, but it could also be
  110. used to get to anything we wanted to store in the record." (quoted by Jamie
  111. McCarthy in comp.sys.mac.prog 10/15/92.)
  112.  
  113. HISTORY:
  114. 8/22/92 dgp wrote it, based on code extracted from my NoiseVBL.c
  115. 8/26/92    dgp    added VBLRemoveAll(), which is automatically placed in the _atexit()
  116.             queue, so it all your VBL tasks will be removed from the queue when
  117.             your program exits, whether normal or abnormally.
  118. 9/9/92    dgp    fixed erroneous attempt to use slot zero when NULL device was passed.
  119. 9/10/92    dgp    added calls to VM to HoldMemory() and UnHoldMemory(). According to Apple's
  120.             Memory book this isn't strictly necessary, since VBL tasks will 
  121.             be called only when it's safe.
  122. 9/17/92    dgp    Transferred FrameSubroutine() here from GDFrameRate.c. Now use 
  123.             FrameSubroutine() instead of SimpleVBLSubroutine() as the default,
  124.             provided we can use Timer.c, otherwise fall back to using 
  125.             SimpleVBLSubroutine.
  126. 10/9/92    dgp    Automatically set up and dispose of the timer used by FrameSubroutine.
  127.             Added a field to the VBLTaskAndA5 structure to hold the timer pointer,
  128.             instead of using up the generic ptr.
  129.             WARNING: old programs (written during 9/92) that explicitly request use of 
  130.             FrameSubroutine must be changed, because at that time it was the user's 
  131.             responsibility to set up and dispose of the timer, whereas it's now done 
  132.             for you. To remind you to make this change "FrameSubroutine" is no longer 
  133.             in VideoToolbox.h, it's treated as a private routine here. To obtain the 
  134.             services of FrameSubroutine, just specify a NULL in the VBLTaskAndA5 
  135.             subroutine field.
  136. 11/17/92 dgp In VBLRemove(), first disable the interrupt, then clean up.
  137.             Fixed error that could cause bus error in VBLRemoveAll.
  138.             VBLInstall() now installs VBLRemoveAll() only once in the _atexit()
  139.             queue, no matter how many times you call it.
  140. 11/24/92 dgp Minor updating of comments.
  141. 7/9/93    dgp    Test MATLAB in if() instead of #if. 
  142. */
  143. #include "VideoToolbox.h"
  144. #include <Traps.h>
  145. void VBLRemoveAll(void);
  146. static void FrameSubroutine(VBLTaskAndA5 *vblData);
  147.  
  148. /* This is just for reference. The original is in VideoToolbox.h
  149. struct VBLTaskAndA5 {
  150.     volatile VBLTask vbl;
  151.     long ourA5;
  152.     void (*subroutine)(struct VBLTaskAndA5 *vblData);
  153.     GDHandle device;
  154.     long slot;
  155.     volatile long newFrame;                // Boolean
  156.     volatile long framesLeft;            // count down to zero
  157.     long framesDesired;
  158.     Timer *frameTimer;                    // time ms since last VBL interrupt, see Timer.c
  159.     void *ptr;                            // use this for whatever you want
  160. };
  161. typedef struct VBLTaskAndA5 VBLTaskAndA5;
  162. */
  163. #define TASK_SIZE 1000    // Generous guess for size of routine
  164. static long vmPresent=0;
  165.  
  166. OSErr VBLInstall(VBLTaskAndA5 *vblData,GDHandle device,int frames)
  167. // trivial, but verbose
  168. {
  169.     static int firstTime=1,slotRoutinesAvailable;
  170.     static long timeManagerVersion=0;
  171.     
  172.     if(firstTime){
  173.         firstTime=0;
  174.         slotRoutinesAvailable=TrapAvailable(_SlotVInstall);
  175.         Gestalt(gestaltVMAttr,&vmPresent);
  176.         vmPresent &= gestaltVMPresent;
  177.         if(!MATLAB)_atexit(VBLRemoveAll);
  178.         Gestalt(gestaltTimeMgrVersion,&timeManagerVersion);
  179.     }
  180.     vblData->device=device;
  181.     if(device!=NULL && slotRoutinesAvailable)vblData->slot=GetDeviceSlot(device);
  182.     else vblData->slot=-1;
  183.     vblData->vbl.vblAddr=(ProcPtr)VBLInterruptServiceRoutine;
  184.     vblData->vbl.qType=vType;
  185.     vblData->vbl.vblCount=0;    /* Initially disable the interrupt service routine */
  186.     vblData->vbl.vblPhase=0;
  187.     vblData->ourA5=SetCurrentA5();
  188.     if(vblData->subroutine==NULL){
  189.         if(timeManagerVersion>=gestaltRevisedTimeMgr){
  190.             vblData->frameTimer=NewTimer();
  191.             StartTimer(vblData->frameTimer);
  192.             vblData->subroutine=FrameSubroutine;
  193.         }
  194.         else vblData->subroutine=SimpleVBLSubroutine;
  195.     }
  196.     vblData->newFrame=0;
  197.     vblData->framesLeft=vblData->framesDesired=frames;
  198.     if(vmPresent){
  199.         HoldMemory(vblData,sizeof(*vblData));
  200.         HoldMemory(vblData->vbl.vblAddr,TASK_SIZE);
  201.         HoldMemory(vblData->subroutine,TASK_SIZE);
  202.     }
  203.     if(vblData->slot>=0)return SlotVInstall((QElemPtr)vblData,vblData->slot);
  204.     else return VInstall((QElemPtr)vblData);
  205. }
  206.  
  207. OSErr VBLRemove(VBLTaskAndA5 *vblData)
  208. {
  209.     OSErr error;
  210.  
  211.     // only remove it if we installed it
  212.     if(vblData->vbl.vblAddr != (ProcPtr)VBLInterruptServiceRoutine)return;
  213.     if(vblData->slot>=0)error=SlotVRemove((QElemPtr)vblData,vblData->slot);
  214.     else error=VRemove((QElemPtr)vblData);
  215.     if(vmPresent){
  216.         UnholdMemory(vblData,sizeof(vblData));
  217.         UnholdMemory(vblData->vbl.vblAddr,TASK_SIZE);
  218.         UnholdMemory(vblData->subroutine,TASK_SIZE);
  219.     }
  220.     if(vblData->subroutine==FrameSubroutine && vblData->frameTimer!=NULL)
  221.         DisposeTimer(vblData->frameTimer);
  222.     return error;
  223. }
  224.  
  225. void VBLRemoveAll(void)
  226. {
  227.     QHdrPtr qHeader;
  228.     QElemPtr q;
  229.     
  230.     qHeader=GetVBLQHdr();
  231.     q=qHeader->qHead;
  232.     while(q!=NULL){
  233.         VBLRemove((VBLTaskAndA5 *)q);    // only removes ours
  234.         q=q->qLink;
  235.     }
  236. }    
  237.  
  238. #pragma options(!profile)    // it would be dangerous to call the profiler from here
  239. #pragma options(assign_registers,redundant_loads)
  240. Ptr GetA0(void)=0x2008;    /* MOVE.L A0,D0 */
  241.  
  242. void VBLInterruptServiceRoutine(void)
  243. {
  244.     register long oldA5;
  245.     register VBLTaskAndA5 *vblData;
  246.  
  247.     vblData = (VBLTaskAndA5 *)GetA0();
  248.     oldA5 = SetA5(vblData->ourA5);
  249.     (*vblData->subroutine)(vblData);        // call user's task, pass data ptr
  250.     SetA5(oldA5);
  251. }
  252.  
  253. void SimpleVBLSubroutine(VBLTaskAndA5 *vblData)
  254. {
  255.     vblData->newFrame=1;
  256.     if(--vblData->framesLeft>0) vblData->vbl.vblCount=1;
  257. }
  258.  
  259. static void FrameSubroutine(VBLTaskAndA5 *vblData)
  260. {
  261.     // The 1991-2 Apple video cards emit several vbl interrupts per frame,
  262.     // which violates Apple's documentation.
  263.     // So we use the Time Manager to ignore any interrupt that occurs within 5 ms
  264.     // of the most recent interrupt, for that video device.
  265.     // Thus this frame counter should work correctly on all video cards.
  266.     // Suggested by Raynald Comtois.
  267.     if(StopTimer(vblData->frameTimer)>5000){
  268.         vblData->newFrame=1;                                    // set new-frame flag
  269.         if(--vblData->framesLeft>0) vblData->vbl.vblCount=1;    // re-enable interrupt
  270.     }else vblData->vbl.vblCount=1;                                // re-enable interrupt
  271.     StartTimer(vblData->frameTimer);
  272. }
  273.  
  274.